<?php

namespace Api\Controller;

class EmailController extends ApiController {

    private $aWarn;

    function __construct() {
        parent::__construct();
        $this->aWarn = array(
            'longerday' => '邮件链接已过期！',
            'noemail' => '邮件链接不匹配！',
            'nomatch' => '邮件不必配',
            'already' => '邮箱已经验证',
            'noalready'=>'邮箱还没有验证，可以直接修改',
            'success'=>'成功！',
            'oserror' => '系统错误，请重试！',
        );
    }

    function verifyemail() {
        $sCode = I('get.code');
        list($sUsername, $sEmail, $sDay) = explode('|', base64_decode($sCode));
        $aDate = array(
            substr(md5(date('d', time()) . md5($sUsername . $sEmail)), 2, 10),
            substr(md5(date('d', time() - 86400) . md5($sUsername . $sEmail)), 2, 10),
        );
        if (!in_array($sDay, $aDate)) {
            $this->show($this->aWarn['longerday']);
        }
        if (!preg_match('/^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/', $sEmail)) {
            $this->show($this->aWarn['nomail']);
        }
        $mUser = D('Users');        
        $aUser = $mUser->findUserbyUsername($sUsername);
        if (!$aUser['email'] || $aUser['email'] != $sEmail) {
            $this->show($this->aWarn['nomatch']);
        }
        if ($aUser['emailstatus']) {
            $this->show($this->aWarn['already']);
        }
        $updata = array('emailstatus' => 1);
        if ($mUser->upUser($aUser['id'], $updata)) {
            $this->show($this->aWarn['success']);
        } else {
            $this->show($this->aWarn['oserror']);
        }

    }

    function changemail() {
       $sCode = I('get.code');
        list($sUsername, $sEmail, $sDay) = explode('|', base64_decode($sCode));
        $aDate = array(
            substr(md5(date('d', time()) . md5($sUsername . $sEmail)), 2, 10),
            substr(md5(date('d', time() - 86400) . md5($sUsername . $sEmail)), 2, 10),
        );
        if (!in_array($sDay, $aDate)) {
            $this->show($this->aWarn['longerday']);
        }
        if (!preg_match('/^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/', $sEmail)) {
            $this->show($this->aWarn['nomail']);
        }
        $mUser = D('Users');
        $aUser = $mUser->findUserbyUsername($sUsername);
        if (!$aUser['emailstatus']) {
            $this->show($this->aWarn['noalready']);
        }
        if ($aUser['email'] == $sEmail) {
            $this->show($this->aWarn['noemail']);
        }
        $updata = array('email' => $sEmail);
        if ($mUser->upUser($aUser['id'], $updata)) {
            $this->show($this->aWarn['success']);
        } else {
            $this->show($this->aWarn['oserror']);
        }
    }

    protected function show($sWarn) {
        echo $sWarn;
        die;
    }

}
